<template>
  <a-modal
    :visible="visible"
    title=""
    centered
    @cancel="onClose"
    :width="1000"
    :footer="null"
    v-bind="$attrs"
  >
    <div
      style="
        font-size: 20px;
        font-weight: bold;
        text-align: center;
        margin-bottom: 20px;
      "
    >
      提示词模板
    </div>

    <a-layout style="border-top: 1px solid #f1f1f1">
      <a-layout-sider width="200" style="background: #fff">
        <div class="menu-wrap beauty-scroller-bar">
          <a-menu
            mode="inline"
            v-model:openKeys="openKeys"
            v-model:selectedKeys="selectedKeys"
            @click="handleMenuClick"
          >
            <a-menu-item :key="-1"> 全部 </a-menu-item>
            <a-sub-menu v-for="item of categoryList" :key="item.id">
              <template #icon>
                <img
                  :src="item.cat_icon"
                  alt=""
                  class="tree-item-icon"
                  style="width: 24px; height: 24px; object-fit: cover"
                  v-if="item.cat_icon"
                />
              </template>
              <template #title>{{ item.cat_name }}</template>
              <template v-if="item.sub && item.sub.length > 0">
                <a-menu-item v-for="child of item.sub" :key="child.id">
                  {{ child.cat_name }}
                </a-menu-item>
              </template>
            </a-sub-menu>
          </a-menu>
        </div>
      </a-layout-sider>
      <a-layout style="padding: 20px">
        <div class="flex">
          <div class="flex-1">
            <div style="">
              <a-input
                v-model:value="keywords"
                placeholder="请输入提示词"
                size="large"
                allowClear
                ref="keywordsInputRef"
                @change="onKeywordsChange"
              />
            </div>
            <a-layout-content
              :style="{
                padding: '0',
                margin: 0,
                minHeight: '280px',
              }"
            >
              <div
                class="list-wrap beauty-scroller-bar"
                @scroll="onListScroll"
                ref="listWrapRef"
              >
                <template v-if="noData">
                  <div class="empty-wrap">
                    <a-empty description="未找到相关提示词" />
                  </div>
                </template>
                <template v-else>
                  <div class="list-item cursor-pointer" v-for="(item, index) of list" :key="index" @click="onItemClick(item)">
                    <div class="list-item-title">{{ item.title }}</div>
                    <a-tooltip :getPopupContainer="getPopupContainer">
                      <template #title>
                        {{ item.description }}
                      </template>
                      <div class="list-item-content">{{ item.description }}</div>
                    </a-tooltip>
                    <div class="list-item-desc">
                      <div style="color: #999">
                        <CheckCircleOutlined />
                        <span style="padding-left: 5px">{{
                          item.use_num >= 100 ? item.use_num : "小于100"
                        }}</span>
                      </div>
                      <!-- <a-button
                        type="primary"
                        ghost
                        class="list-item-button"
                        @click="onItemClick(item)"
                        >使用</a-button
                      > -->
                    </div>
                  </div>
                  <div class="tips">
                    <span v-if="listLoading">
                      <LoadingOutlined />
                      加载中
                    </span>
                    <span v-if="hasMore">上拉加载更多</span>
                    <span v-if="noMore">没有更多了</span>
                  </div>
                </template>
              </div>
            </a-layout-content>
          </div>
          <div class="pl-20 flex flex-col" style="width: 30%; min-width: 200px;">
            <a-textarea class="flex-1" placeholder="请选择提示词" v-model:value="systemPrompt"></a-textarea>
            <div class="mt-10 flex justify-between">
              <a-button shape="round" style="width: 40%;" @click="onUseClick">使用</a-button>
              <a-button shape="round" style="width: 40%;" @click="onSendClick">发送</a-button>
            </div>
          </div>
        </div>
      </a-layout>
    </a-layout>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  ref,
  nextTick,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message } from "ant-design-vue";
import { LoadingOutlined, CheckCircleOutlined } from "@ant-design/icons-vue";
import _ from 'lodash'

let inputTimer = null;

export default defineComponent({
  name: "PromptsUse",
  components: { LoadingOutlined, CheckCircleOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },

  setup(props, context) {
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      page: 1,
      pageSize: 20,
      total: 0,
      noData: false,

      keywords: "",
      list: [],
      hasMore: false,
      noMore: false,
      listLoading: false,

      categoryList: [],
      selectedKeys: [-1],
      openKeys: [],
      currentCateId: 0,
    });
    console.log('11231312313131');
    const getList = (loadMore) => {
      let params = {
        page: state.page,
        pageSize: state.pageSize,
      };
      if (state.keywords) {
        params.keywords = state.keywords;
      }
      if (state.currentCateId > 0) {
        params.cat_id = state.currentCateId;
      }
      state.hasMore = false;
      state.noMore = false;
      state.listLoading = true;
      request
        .get("/work_ai", "/user/promptWords/list", { ...params })
        .then((res) => {
          state.listLoading = false;
          state.total = res.total;
          if (res.list && res.list.length > 0) {
            state.noData = false;
            if (loadMore) {
              state.list = state.list.concat(res.list);
            } else {
              state.list = res.list;
            }

            if (state.page * state.pageSize < state.total) {
              state.hasMore = true;
            } else {
              state.noMore = true;
            }
          } else {
            state.noData = true;
          }
        });
    };

    const onKeywordsChange = (e) => {
      if (inputTimer) {
        clearTimeout(inputTimer);
        inputTimer = null;
      }
      inputTimer = setTimeout(() => {
        state.page = 1;
        getList();
      }, 500);
    };

    const onItemClick = (item, replace = false) => {
      if (item.content_matches && item.content_matches.length > 0 && !replace) {
        context.emit("onSearchSelect", item);
      }
      systemPrompt.value = item.content
      selectedPrompt.value = item
    };

    const listWrapRef = ref();
    // 监听列表滚动,到底部请求下一页数据
    const onListScroll = (e) => {
      if (e.target.scrollTop + 501 >= listWrapRef.value.scrollHeight) {
        if (state.hasMore) {
          state.page++;
          getList(true);
        }
      }
    };

    const onClose = () => {
      context.emit("onClose");
    };

    getList();

    const keywordsInputRef = ref(null);

    const handleMenuClick = ({ item, key, keyPath }) => {
      state.currentCateId = key;
      state.page = 1;
      getList();
    };

    const getCategoryList = () => {
      request
        .get("/work_ai", "/user/promptWords/category/list", {})
        .then((res) => {
          if (res.result) {
            state.openKeys = [];
            if (res.result.length > 0) {
              state.openKeys.push(res.result[0].id);
            }
            state.categoryList = res.result;
          }
        });
    };

    const init = () => {
      // input自动聚焦
      nextTick(() => {
        keywordsInputRef.value.focus();
      });
      getCategoryList();
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          systemPrompt.value = ''
          selectedPrompt.value = null
        }
      }
    );

    let selectedPrompt = ref(null)
    let systemPrompt = ref('')

    const getPopupContainer = (trigger) => {
      return trigger.parentNode;
    };

    const onUseClick = () => {
      if (! systemPrompt.value) {
        message.error('请选择提示词')
        return
      }
      
      let item = _.cloneDeep(selectedPrompt.value)
      item.content = systemPrompt.value
      
      context.emit('use', item)
    }

    const onSendClick = () => {
      if (! systemPrompt.value) {
        message.error('请选择提示词')
        return
      }

      let item = _.cloneDeep(selectedPrompt.value)
      item.content = systemPrompt.value

      context.emit('send', item)
    }

    return {
      ...toRefs(state),
      onClose,
      onKeywordsChange,
      onItemClick,
      onListScroll,
      listWrapRef,
      keywordsInputRef,
      handleMenuClick,
      getPopupContainer,
      systemPrompt,
      onUseClick,
      onSendClick,
    };
  },
});
</script>

<style lang="less" scoped>
.list-wrap {
  width: 100%;
  height: 420px;
  overflow: hidden auto;
  margin-top: 20px;
  padding-right: 10px;

  .empty-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .list-item {
    width: 100%;
    padding: 10px 20px;
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 15px;
    border: 1px solid #ddd;

    .list-item-title {
      font-weight: 600;
      font-size: 16px;
      margin-bottom: 5px;
    }

    .list-item-content {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      color: #999;
    }

    .list-item-desc {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-top: 20px;
      margin-bottom: 10px;
    }

    .list-item-button {
      border-radius: 4px;
      padding: 0 24px;

      &:hover {
        background-color: @primary-color !important;
        color: #fff !important;
      }
    }
  }

  .tips {
    padding: 10px 0;
    text-align: center;
    color: #999;
  }
}

.menu-wrap {
  width: 100%;
  height: 520px;
  overflow: hidden auto;
}

:deep(.ant-tooltip-content) {
  width: 520px;
}
</style>
